package com.ruoyi.service.Impl;

import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.mapper.MemberMapper;
import com.ruoyi.model.LoginMember;
import com.ruoyi.model.Member;
import com.ruoyi.service.MemberService;
import com.ruoyi.system.api.model.LoginUser;
import com.ruoyi.utils.JwtUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Author:Jiang
 * @Date: 2023/08/11/ 10:57
 **/
@Service
public class MemberServiceImpl implements MemberService {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MemberMapper memberMapper;

    @Override
    public Map<String,Object> login(Member member) {
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(member.getTel(),member.getPassword());
        //认证用户输入的用户名密码是否合法
        Authentication authentication=authenticationManager.authenticate(authenticationToken);
        //认证没有通过，给出提示信息
        if(Objects.isNull(authentication)){
            throw new RuntimeException("用户名或密码错误!");
        }
        //如果认证通过，使用userId生成jwt，将用户的信息存入redis
        LoginMember loginMember= (LoginMember) authentication.getPrincipal();

        String memberId=loginMember.getMember().getId().toString();
        String jwt = JwtUtil.createJWT(memberId);
        //
        redisTemplate.opsForValue().set("login:"+memberId,loginMember.getMember());
        SecurityContextHolder.getContext().setAuthentication(authentication);
        Map<String,Object> map=new HashMap<>();
        map.put("token",jwt);
        map.put("member",loginMember);
        return map;
    }

    @Override
    public Boolean logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginMember loginmember = (LoginMember) authentication.getPrincipal();
        String memberId = loginmember.getMember().getId().toString();
        Boolean result = redisTemplate.delete("login:" + memberId);
        return result;
    }

    @Override
    public int insertMember(Member member) {
        member.setPassword(SecurityUtils.encryptPassword(member.getPassword()));
        return memberMapper.insertMember(member);
    }


}
